package com.team.coupon.controller;

import com.team.common.core.web.domain.AjaxResult;
import com.team.coupon.domain.dto.BizConsumeCouponDto;
import com.team.coupon.domain.dto.BizUserCouponDto;
import com.team.coupon.exception.CustomException;
import com.team.coupon.service.BizUserCouponService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "优惠券抢购管理", description = "优惠券相关接口")
@RestController
@RequestMapping("/coupon")
public class BizUserCouponController {

    @Autowired
    private BizUserCouponService bizUserCouponService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 抢购优惠券
    @PostMapping("/grab")
    @GetMapping("/grab")
    public AjaxResult grabCoupon(@RequestBody BizUserCouponDto bizUserCoupon) {
        /*测试用法
        BizUserCouponDto bizUserCoupon = new BizUserCouponDto();
        bizUserCoupon.setUserId(1L);
        bizUserCoupon.setCouponId(11L);*/
        try{
            return AjaxResult.success(bizUserCouponService.grabCoupon(bizUserCoupon));
        }catch (CustomException e){
            //log.error("抢券失败", e);
            return AjaxResult.error(e.getMsg());
        }
    }

    // 根据用户id和发布主体id查询在该商铺可以使用的优惠券
    @GetMapping("/list")
    public AjaxResult listCouponsByUserIdAndEntityId(@RequestParam("userId") Long userId,
                                                     @RequestParam("entityId") Long entityId) {
        try{
            return AjaxResult.success(bizUserCouponService.listCouponsByUserIdAndEntityId(userId, entityId));
        }catch (CustomException e){
            //log.error("抢券失败", e);
            return AjaxResult.error(e.getMsg());
        }
    }

    // 使用优惠券
    @PostMapping("/consumeCoupon")
    public AjaxResult consumeCoupon(@RequestBody BizConsumeCouponDto bizConsumeCouponDto) {
        try{
            return AjaxResult.success(bizUserCouponService.consumeCoupon(bizConsumeCouponDto));
        }catch (CustomException e){
            //log.error("使用失败", e);
            return AjaxResult.error(e.getMsg());
        }
    }

    // 根据用户id查找用户所有的优惠券
    @GetMapping("/listByUserId")
    public AjaxResult listCouponsByUserId(@RequestParam("userId") Long userId) {
        try{
            return AjaxResult.success(bizUserCouponService.listCouponsByUserId(userId));
        }catch (CustomException e){
            //log.error("查询失败", e);
            return AjaxResult.error(e.getMsg());
        }
    }


}
